// store/permission.js
import { asyncRouter, constantRoutes } from '@/router';

function hasPermission(roles, route) {
    if (route.meta && route.meta.roles) {
        // 如果当前路由有配置权限 则判断用户是否有权限
        return roles.some(role => route.meta.roles.indexOf(role) >= 0)
    } else {
        return true
    }
}

const permission = {
    state: {
        routers: constantRoutes,
        addRouters: []
    },
    mutations: {
        SET_ROUTERS: (state, routers) => {
            state.addRouters = routers;
            state.routers = constantRoutes.concat(routers);
        }
    },
    actions: {
        GenerateRoutes({ commit }, data) {
            return new Promise(resolve => {
                const { roles } = data;
                const accessedRouters = asyncRouter.filter(v => {
                    // 超级admin权限 直接返回所有路由
                    if (roles.indexOf('super') >= 0) return true;
                    // 没有配置权限的路由 也直接返回
                    if (hasPermission(roles, v)) {
                        // 如果是一级路由
                        if (v.children && v.children.length > 0) {
                            // 过滤二级路由
                            v.children = v.children.filter(child => {
                                // 如果二级路由有配置权限 则判断用户是否有权限
                                if (hasPermission(roles, child)) {
                                    return child
                                }
                                return false;
                            });
                            return v
                        } else {
                            return v
                        }
                    }
                    return false;
                });
                commit('SET_ROUTERS', accessedRouters);
                resolve();
            })
        }
    }
};

export default permission;
